'''
Created on Jun 9, 2010

@author: Behrooz Nobakht
'''
from amscms.core.widgets.jalali import convert_to_jalali
from django.template import TemplateSyntaxError, Node, Variable, \
    VariableDoesNotExist, Library
import time
import datetime

register = Library()

@register.tag(name="jalali_view")
def do_jalali_view(parser, token):
    try:
        tag_name, the_date = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    return JalaliDateNode(the_date)

def gregorian_to_jalali(date):
    try:
        tuple = date.timetuple()
        t = time.mktime(tuple)
        jd = convert_to_jalali(t)
        result = str(jd[0]) + "/" + str(jd[1]) + "/" + str(jd[2])
        return result
    except:
        return '?-?-?'
    
def gregorian_string_to_jalali(date):
    d = datetime.datetime.strptime(date, "%Y-%m-%d")
    return gregorian_to_jalali(d)
    
    
class JalaliDateNode(Node):
    
    def __init__(self, the_date):
        self.the_date = Variable(the_date)
        
    def render(self, context):
        try:
            context_value = self.the_date.resolve(context)
            return gregorian_to_jalali(context_value)
        except VariableDoesNotExist:
            return '?-?-?'
            
    
